package com.jay.tools.web.route;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import androidx.core.content.ContextCompat;
import android.webkit.URLUtil;
import android.webkit.WebView;

import com.jay.tools.base.BaseFragment;
import com.jay.tools.utils.LogUtil;
import com.jay.tools.web.WebFragment;
import com.jay.tools.web.WebFragmentImpl;

/**
 * author: tanjianpei
 * date: 2018/8/22 022 15:19
 * <p>
 * description: 供自定义webView框架内部使用，外部不可调用此类
 */
public class Router {

    private final String TAG = "Router";

    private Router() {

    }

    private static class Holder {
        private static final Router INSTANCE = new Router();
    }

    public static Router getInstance() {
        return Holder.INSTANCE;
    }

    /**
     * 强制webview内部链接使用自身规则打开页面
     *
     * @param fragment
     * @param url
     * @return
     */
    public final boolean handleWebUrl(WebFragment fragment, String url) {
        if (url.contains("tel:")) {
            callPhone(fragment.getContext(), url);
            return true;
        }

//        jumpWithBottom(fragment, url);
        jumpWithOutBottom(fragment, url);
        return true;
    }

    /**
     * WebView 加载页面
     *
     * @param fragment
     */
    public final void loadPage(WebFragment fragment) {
        WebView webView = fragment.getWebView();
        if (null == webView) {
            LogUtil.e(TAG, "webview is null");
            return;
        }
        String url = fragment.getUrl();
        // URLUtil Android原生提供的方法
        if (URLUtil.isNetworkUrl(url) || URLUtil.isAssetUrl(url)) {
            webView.loadUrl(url);
        } else {
            webView.loadUrl("file:///android_asset/" + url);
        }
    }

    private void jumpWithOutBottom(WebFragment fragment, String url) {
        //全屏打开，不带底部导航栏
        final BaseFragment parentFragment = fragment.getTopFragment();
        WebFragmentImpl webFragment = WebFragmentImpl.newInstance(url);
        parentFragment.start(webFragment);
    }

    private void jumpWithBottom(WebFragment fragment, String url) {
        //非全屏打开，带底部导航栏
        final BaseFragment parentFragment = fragment.getParentDelegate();
        final WebFragment webFragment = WebFragmentImpl.newInstance(url);
        if (null == parentFragment) {
            fragment.start(webFragment);
        } else {
            parentFragment.start(webFragment);
        }
    }

    private void callPhone(Context context, String url) {
        final Intent intent = new Intent(Intent.ACTION_DIAL);//将电话放到电话栏，由用户决定是否拨打
        final Uri data = Uri.parse(url);
        intent.setData(data);
//        context.startActivity(intent);
        // 推荐使用方法：
        ContextCompat.startActivity(context, intent, null);
    }
}
